// pages/Order/SubmitTravelOrder/SubmitTravelOrder.js
//获取应用实例
const app = getApp()
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { queryAppInforMation } from '../../../api/brand';
import { queryTravelUser , addTravelOrderForm , payTravelOrderForm } from '../../../api/travel';
import { checkUserPasswordIsSet } from '../../../api/login';
import { getUserAccount , queryUserWechatOpenId } from '../../../api/user';
const regeneratorRuntime = require('../../../common/runtime');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    assetsAddress: assetsAddress,
    travel: {}, // 旅游项目信息
    planId: '', // 套餐ID
    plan: {}, // 套餐信息
    planDateId: '', // 套餐日期ID
    planDate: {}, // 套餐日期信息
    number: 1, // 订单数量
    price: 1, // 套餐价格
    contactName: '', // 联系人姓名
    contactPhone: '', // 联系人手机号
    message: '', // 买家留言
    travelUserId: '', // 出行人ID，字符串数组
    travelUserList: [], // 出行人列表
    selTravelUserList: [], // 所选出行人列表
    selTravelUserListId: [], // 复选框所选出行人列表ID
    travelUserPop: false,
    checkBox: true,
    orderPayPop: false,
    payType: [2],
    balance: 0,
    payPassword: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.travelItem){
      var travelItem = JSON.parse(options.travelItem);
      console.log(travelItem,'travelItem');
      this.setData({
        travel: travelItem.travel,
        planId: travelItem.planId,
        plan: travelItem.plan,
        planDateId: travelItem.planDateId,
        planDate: travelItem.planDate,
        price: travelItem.planDate.amount,
      })
      this._queryTravelUser({init: true});
    }
    this._queryUserWechatUnionId();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this._getUserAccount('0');
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  // 购买数量切换
  onNumChange(e){
    this.setData({
      number: e.detail,
      price: e.detail * this.data.planDate.amount,
    })
    if(e.detail < this.data.selTravelUserList.length){
      let list = [];
      let listId = [];
      for (let index = 0; index < e.detail; index++) {
        const item = this.data.selTravelUserList[index];
        list.push(item);
        listId.push(item.id + '');
      }
      this.setData({
        selTravelUserList: list,
        selTravelUserListId: listId,
      })
    }
  },
  // 查看预订须知
  showNotice(){
    var typeName = '机票套餐';
    const itemType = this.data.travel.itemType;
    switch (itemType) {
      case 2:
        typeName = '酒店套餐'
        break;
      case 4:
        typeName = '游艇租赁'
        break;
      case 5:
        typeName = '尾波冲浪'
        break;
      case 6:
        typeName = '游艇出海'
        break;
      default:
        break;
    }
    typeName = `${typeName}预订须知`;
    this._queryAppInforMation({title: typeName});
  },
  _queryAppInforMation({title}){
    queryAppInforMation({infoType: '2',title: title,})
    .then(res => {
      if(res.success){
        if(res.data.content.length > 0){
          var itm = res.data.content[0];
          if(itm.imgUrl){
            wx.navigateTo({
              url: `/pages/Link/LinkImg/LinkImg?url=${encodeURIComponent(itm.imgUrl)}&title=${JSON.stringify(item.label)}`,
            })
          }else if(itm.jumpUrl && itm.jumpUrl.length > 4 && itm.jumpUrl.substring(0,4) == 'http'){
            wx.navigateTo({
              url: `/pages/Link/Link/Link?url=${encodeURIComponent(itm.jumpUrl)}&title=${JSON.stringify(item.label)}`,
            })
          }else if(res.data.content[0].content){
            wx.navigateTo({
              url: `/pages/Link/LinkText/LinkText?content=${JSON.stringify(itm.content)}&title=${JSON.stringify(item.label)}`,
            })
          }
        }else{
          wx.showToast({
            title: '敬请期待',
            icon: 'none',
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 查询出行人
  _queryTravelUser({init}){
    let _this = this;
    queryTravelUser({page: 0,size: 99})
    .then(res => {
      if(res.success){
        _this.setData({
          travelUserList: res.data.content,
        })
        if(init){
          _this.setData({
            selTravelUserList: _this.data.travelUserList.length > 0 ? [_this.data.travelUserList[0]] : [],
            selTravelUserListId: _this.data.travelUserList.length > 0 ? [_this.data.travelUserList[0].id] : []
          })
        }
        _this.setData({
          selTravelUserListId: _this.data.selTravelUserListId,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 更多出行人
  showTravelUserList(){
    var list = [];
    for (let index = 0; index < this.data.selTravelUserList.length; index++) {
      const item = this.data.selTravelUserList[index];
      list.push(item.id + '');
    }
    this.setData({
      travelUserPop: true,
      selTravelUserListId: list,
    })
  },
  onTravelUserPopClose(){
    this.setData({
      travelUserPop: false,
    })
  },
  // 添加出行人
  addTravelUser(){
    let _this = this;
    wx.navigateTo({
      url: `/pages/Users/AddTravelUser/AddTravelUser`,
      events: {
        'updateTravelUser': function(data){
          _this._queryTravelUser({});
        }
      }
    })
  },
  // 删除选择出行人
  delSelTravelPop(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    var index = this.data.selTravelUserList.findIndex(itm => itm.id == item.id);
    var list = this.data.selTravelUserList;
    list.splice(index,1);
    this.setData({
      selTravelUserList: list,
    })
  },
  // 修改联系人信息
  updateTravelUser(e){
    let _this = this;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    wx.navigateTo({
      url: `/pages/Users/AddTravelUser/AddTravelUser?id=${item.id}`,
      events: {
        'updateTravelUser': function(data){
          _this._queryTravelUser({init: true});
        }
      }
    })
  },
  // 选择出行人
  onSelTravelPeoChange(e){
    console.log(e.detail,'e.detail')
    var orderSum = this.data.number * this.data.plan.number;
    console.log(orderSum);
    if(e.detail.length > orderSum){
      wx.showToast({
        title: `最大游玩人数为${orderSum}`,
        icon: 'none',
      });
      return;
    }
    this.setData({
      selTravelUserListId: e.detail,
    })
  },
  // 确认选择出行人
  submitSelTravelUser(){
    let _this = this;
    console.log(_this.data.selTravelUserListId,'selId')
    const selTravelUserListId = _this.data.selTravelUserListId;
    const travelUserList = _this.data.travelUserList;
    let list = [];
    for (let index = 0; index < travelUserList.length; index++) {
      const item = travelUserList[index];
      for (let j = 0; j < selTravelUserListId.length; j++) {
        const itm = selTravelUserListId[j];
        if(itm == item.id){
          list.push(item);
        }
      }
    }
    _this.setData({
      selTravelUserList: list,
      travelUserPop: false,
    })
  },
  // 输入框发生变化
  onFieldChange(event){
    // event.detail 为当前输入的值
    console.log(event.detail);
    const name = event.target.dataset.name||event.currentTarget.dataset.name;
    console.log(name,'name')
    var data = this.data;
    data[name] =  event.detail;
    this.setData(data);
  },
  // 条款内容是否同意
  onChange(e){
    this.setData({
      checkBox: e.detail,
    })
  },
  // 阅读合同或协议
  showProtocol(e){
    let title = e.target.dataset.item||e.currentTarget.dataset.item;
    this._queryAppInforMation({title: title});
  },
  // 确认订单
  submitOrder(){
    let _this = this;
    const { checkBox , selTravelUserList , number , plan , contactName , contactPhone } = _this.data;
    if(!checkBox){
      wx.showToast({
        title: '请阅读并同意电子合同和线路标准退预订须知协议',
        icon: 'none',
      });
      return;
    }
    console.log(number * plan.number)
    if(plan.number){
      if(selTravelUserList.length < (number * plan.number)){
        wx.showToast({
          title: `当前所选项目出行人人数为${number * plan.number}，请补充其他出行人信息`,
          icon: 'none',
        });
        return;
      }
    }
    if(contactName == ''){
      wx.showToast({
        title: '请输入联系人姓名信息',
        icon: 'none',
      });
      return;
    }
    if(contactPhone == ''){
      wx.showToast({
        title: '请输入联系人手机信息',
        icon: 'none',
      });
      return;
    }
    this.setData({orderPayPop: true})
    // this._submitOrder();
  },

  // 下单
  _submitOrder(){
    let _this = this;
    addTravelOrderForm({dateId: _this.data.planDate.id,number: _this.data.number,contactName: _this.data.contactName,contactPhone: _this.data.contactPhone,travelUserId: _this.data.selTravelUserListId.join(','),message: _this.data.message,itemType: _this.data.travel.itemType})
      .then(res => {
        if(res.success){
          _this.pay({orderCode:res.data.orderCode,payType:_this.data.payType.indexOf(0) != -1 ? '0' : _this.data.payType[0],amount: _this.data.payType.length > 1 ? _this.data.balance > _this.data.price ? _this.data.price : _this.data.balance : ''})
        }else{
          wx.showToast({
            title: res.errMessage,
            icon: 'none',
          })
        }
      })
  },
  pay({orderCode,payType,amount}){
    let _this = this;
    payTravelOrderForm({isAllPay: '1',payType: payType,orderCode: orderCode,openId: _this.data.unionid,payAmount: amount,payPassword: payType == '0' ? _this.data.payPassword : null}).then(res => {
      if(res.success){
        _this.wechatPay({orderCode: orderCode,payType: payType,wechatSign: res.data ? res.data.data : res.data});
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 支付
  wechatPay({orderCode,payType,wechatSign}){
    let _this = this;
    if(_this.data.payType.indexOf(0) != -1 && payType == 0){
      if(_this.data.payType.length == 1 || _this.data.balance > _this.data.price || _this.data.balance == _this.data.price){
        wx.navigateTo({
          url: '/pages/Order/PaySuccess/PaySuccess',
        })
      }else{
        // 组合支付
        var arr = JSON.parse(JSON.stringify(_this.data.payType));
        arr.splice(arr.indexOf(1),1);
        _this.pay({orderCode: orderCode,payType: arr[0],amount: _this.data.price - _this.data.balance})
      }
    }else{
      // console.log(JSON.parse(wechatSign),'jsonData');
      var order = JSON.parse(wechatSign)
      // TODO微信支付
      wx.requestPayment({
        timeStamp: order.timeStamp.toString(),
        nonceStr: order.nonceStr,
        package: order.package,
        signType: order.signType,
        paySign: order.paySign,
        success: () => {
          wx.navigateTo({
            url: '/pages/Order/PaySuccess/PaySuccess',
          })
        },
        fail: (err) => {
          console.log(err,'err')
          wx.showToast({
            title: '取消支付',
            icon: 'none',
          })
        }
      })
    }
  },
  // 关闭支付方式选择
  orderPayPopClose(){
    this.setData({
      orderPayPop: false,
    })
  },
  // 校验是否设置过支付密码
  _checkUserPasswordIsSet(){
    let _this = this;
    return new Promise((resolve,reject) => {
      checkUserPasswordIsSet({})
      .then(res => {
        if(res.success){
          resolve(true)
        }else{
          resolve(false)
        }
      })
    })
  },
  // 获取用户的Openid
  _queryUserWechatUnionId(){
    let _this = this;
    wx.login({
      success: (logRes) => {
        queryUserWechatOpenId({code: logRes.code})
        .then(res => {
          if(res.success){
            _this.setData({
              unionid: res.data.openid
            })
          }else{
            wx.showToast({
              title: res.errMessage,
              icon: 'none',
            })
          }
        })
      }
    })
  },
  // 获取用户账户余额
  _getUserAccount(type){
    let _this = this;
    getUserAccount(type)
    .then(res => {
      if(res.success){
        if(type == 0){
          _this.setData({
            balance : res.data.balance,
            payType: res.data.balance > 0 ? [0] : []
          })
        }else if(type == 5){
          _this.setData({
            integral : res.data.balance,
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none'
        })
      }
    })
  },
  // 是否选择余额支付
  selBalancePay(){
    if(this.data.balance == 0){
      return;
    }
    var arr = this.data.payType;
    console.log(arr,'arr')
    console.log(arr.indexOf(1))
    this.setData({
      payType: [0],
    })
    // if(arr.indexOf(1) != -1){
    //   arr.splice(arr.indexOf(1),1)
    //   console.log(arr,'arr')
    //   this.setData({
    //     payType: arr,
    //   })
    // }else{
    //   arr.push(1);
    //   this.setData({
    //     payType: arr,
    //   })
    // }
  },
  // 切换支付渠道
  selPayType(e){
    console.log(e);
    let payType = e.target.dataset.type||e.currentTarget.dataset.type;
    var arr = this.data.payType;
    console.log(arr,'arr')
    console.log(arr.indexOf(payType))
    // if(arr.indexOf(payType) != -1){
    //   arr.splice(arr.indexOf(payType),1)
    //   console.log(arr,'arr')
    //   this.setData({
    //     payType: arr,
    //   })
    // }else{
    //   arr.push(payType);
    //   this.setData({
    //     payType: arr,
    //   })
    // }
    this.setData({
      payType: [2]
    })
  },
  // 确认选择支付渠道
  async submitPayOrder(){
    let _this = this;
    if(_this.data.payType.indexOf(0) != -1){
      if(_this.data.payType.length == 1 && _this.data.price > _this.data.balance){
        wx.showToast({
          title: '当前余额不足，请更换其他支付方式，或者组合支付',
          icon: 'none'
        })
        return;
      }
      const isSetPayPassword = await _this._checkUserPasswordIsSet();
      if(!isSetPayPassword){
        var phone = wx.getStorageSync('phone');
        if(phone.length != 11){
          wx.showModal({
            title: '温馨提示',
            content: '当前暂未设置交易密码，设置交易密码之前需要绑定手机号，是否前往绑定？',
            success: (modal) =>{
              if(modal.confirm){
                wx.navigateTo({
                  url: '/pages/Users/BindPhone/BindPhone',
                })
              }
            },
          })
          return;
        }
        wx.showModal({
          title: '温馨提示',
          content: '暂未设置交易密码，是否前往设置？',
          success: (modal) =>{
            if(modal.confirm){
              wx.navigateTo({
                url: '/pages/Users/UpdatePayPassword/UpdatePayPassword',
              })
            }
          },
        })
        return;
      }
      const child = _this.selectComponent('.pay-passwordAuth');
      console.log(child,'child')
      child.clearPassword();
      child.openPayAuth();
    }else{
      _this._submitOrder();
    }
  },
  // 余额支付校验密码成功
  sonSubmitOrder(e){
    console.log(e,'e')
    this.setData({
      payPassword: e.detail,
    })
    this._submitOrder();
  },
})